# Image Robot replaces the image URLs you place in a blip for the actual image
# image-robot@appspot.com
# author: Marti Planellas (beldar.cat@gmail.com)
# in Wave: beldar@wavesandbox.com
# and beldar.cat@googlewave.com

__author__ = 'beldar.cat@gmail.com (Marti Planellas)'

from waveapi import events
from waveapi import model
from waveapi import robot
from waveapi import document
import logging
import re

logger = logging.getLogger('Image Robot')
logger.setLevel(logging.DEBUG)

def OnBlipSubmit(properties, context):
  oblip = context.GetBlipById(properties['blipId'])
  text = oblip.GetDocument().GetText()
  pp = re.compile('(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*\.(?:jpg|gif|png))(?:\?([^#]*))?(?:#(.*))?');
  imatges = pp.findall(text)
  if len(imatges) > 0:
 	 for imatge in imatges:
		imageurl = ''
		o=0
		for tros in imatge:
			if o==0:
				imageurl += 'http://'
			if o!=0:
				imageurl += tros
			o += 1
		logger.debug('Imatge: '+imageurl)
		text = text.split(imageurl)
		oblip.GetDocument().SetText(text[0]+'\n')
		image = document.Image(imageurl)
		oblip.GetDocument().AppendElement(image)
		oblip.GetDocument().AppendText('\n'+text[1])


def OnParticipantsChanged(properties, context):
  added = properties['participantsAdded']
  for p in added:
    Notify(context,p)

def OnRobotAdded(properties, context):
  root_wavelet = context.GetRootWavelet()
  root_wavelet.CreateBlip().GetDocument().SetText("Hi I'm THE Image Robot, I will replace the image URLs you place in a blip for the actual image!")
  logger.debug('robot added')

def Notify(context,p):
  if p != 'last-robot@appspot.com':
   root_wavelet = context.GetRootWavelet()
   #root_wavelet.CreateBlip().GetDocument().SetText("Hi "+p+" type 'YourLastFMUser-is-listening' and I will tell you what song are you listening!")

if __name__ == '__main__':
  imager = robot.Robot('Image Robot', 
      version='1',
	  image_url='http://image-robot.appspot.com/assets/image.png',
      profile_url='http://image-robot.appspot.com/')
  imager.RegisterHandler(events.WAVELET_PARTICIPANTS_CHANGED, OnParticipantsChanged)
  imager.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded)
  imager.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmit)
  imager.Run(debug=True)